﻿using _8Group.MES.Meng_IService;
using _8Group.MES.MengIService;
using _8Group.MES.MengIService.DTO;
using _8Group.MES.Model.WM仓储管理;
using FourGroups.Project;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace _8Group.MES.MengService
{
    [ApiExplorerSettings(GroupName = "孟祥宇")]
    public class StockService : ApplicationService, IStockService
    {
        /// <summary>
        /// 供应商表
        /// </summary>
        private readonly IRepository<WM_Stock_Detail, int> _stockDetailRepository;
        public StockService(IRepository<WM_Stock_Detail, int> stockDetailRepository)
        {
            _stockDetailRepository = stockDetailRepository;
        }
        public async Task<string> GetStockAsync(string? itemCode, string? itemName, string? batchCode, string? wareHouseName, int page, int limit )
        {
            var stock =await _stockDetailRepository.GetQueryableAsync();

            stock= stock.WhereIf(!string.IsNullOrEmpty(itemCode), x => x.ItemCode.Contains(itemCode));
            stock= stock.WhereIf(!string.IsNullOrEmpty(itemName), x => x.ItemName.Contains(itemName));
            stock= stock.WhereIf(!string.IsNullOrEmpty(batchCode), x => x.BatchCode.Contains(batchCode));
            stock= stock.WhereIf(!string.IsNullOrEmpty(wareHouseName), x => x.WarehouseName.Contains(wareHouseName));
            int totalCount = stock.Count();

            stock = stock.OrderByDescending(c=>c.Id).Skip
                ((page - 1) * limit).Take(limit);

            return JsonConvert.SerializeObject(new { code = "0", data = stock.ToList(), count = stock.Count(), msg = "success" }, Formatting.Indented);
        }
        /// <summary>
        /// 添加库存
        /// </summary>
        /// <param name="stock"></param>
        /// <returns></returns>
        public async Task<int> AddStockAsync(StockDTO stock)
        {
            var n = AutoMapperExt.MapTo<WM_Stock_Detail>(stock);
            await _stockDetailRepository.InsertAsync(n);
            return 1;
        }
        /// <summary>
        /// 供应商删除
        /// </summary>
        /// <param name="mdvendor"></param>
        /// <returns></returns>
        public async Task<int> DeleteStockAsync(int id)
        {
            await _stockDetailRepository.DeleteAsync(id, true);
            return 1;
        }
        /// <summary>
        /// 供应商修改
        /// </summary>
        /// <param name="mdvendor"></param>
        /// <returns></returns>
        public async Task<int> UpdateStockAsync(UpdateStockDTO stock)
        {
            var n = AutoMapperExt.MapTo<WM_Stock_Detail>(stock);
            await _stockDetailRepository.UpdateAsync(n);
            return 1;
        }
    }
}
